﻿using Microsoft.Xna.Framework;
using PhantomRealm.Common.Systems;
using PhantomRealm.Common.Utilities;
using PhantomRealm.Content.Skies.Overlays;
using System;
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.ModLoader;

namespace PhantomRealm.Common.Players
{
    public class AuroraPlayer : ModPlayer
    {
        public bool AuroraActive => GetAuroraType() != -1;
        public bool InLocalAurora => auroraVisuals.Any(x => x.Value > 0);
        private const byte Duration = 30;
        private int _priority = -1;
        private readonly Dictionary<int, byte> auroraVisuals = new() { { AuroraOverlay.BASIC, 0 } };
        public void SetLocalAurora(int type)
        {
            if (_priority == -1)
            {
                auroraVisuals[type] = (byte)Math.Min(auroraVisuals[type] + 1, Duration);
                _priority = type;
            }
        }
        public float GetAuroraIntensity(int type) => MathHelper.Clamp(auroraVisuals[type] / (float)Duration * 1.25f, 0, 1);
        public void Reset()
        {
            for (int i = 0; i < AuroraOverlay.COUNT; i++)
            {
                if (i != _priority)
                {
                    auroraVisuals[i] = (byte)Math.Max(auroraVisuals[i] - 1, 0);
                }
            }
            _priority = -1;
        }

        public override void PostUpdateMiscEffects()
        {
            if (!Main.dedServ && Player.whoAmI == Main.myPlayer)
            {
                int type = GetAuroraType();
                if (type != -1)
                {
                    SetLocalAurora(type);
                }
                Player.ManageSpecialBiomeVisuals("PhantomRealm:AuroraSky", InLocalAurora);
            }
        }

        private int GetAuroraType()
        {
            if (Player.IsDay() || !AuroraSystem.AuroraActive || Main.raining && !Player.ZoneSnow() || Player.ZoneCorrupt() || Player.ZoneCrimson())
            {
                return -1;
            }
            if (Player.ZoneSnow() || Player.ZoneSky())
            {
                return AuroraOverlay.BASIC;
            }
            return -1;
        }
    }
}